$(document).ready(function(){
	$('.el-modal-show').aModal().click();
	$('input').emulationInput();
	$('.bl-ds').tabsDetails();
	$('.bl-ls').actionTable();
	$('.el-help').aTooltip();
	$('.bl-hd-location select').hSelect();
	
	$('.bl-ls-search').aSearch();
	$('.bl-ds').actionDetails();
	$('.bl-st').actionSettings();
	$('.un-ds-note .el-help a').aTooltip({tipClass:'bl-side-tip', xOffset:270});
	$('.bl-ls-place .el-btn-blue').aModal({modalCustom:'#modal_allow_complete'});
	$('.bl-db article').dHover();
});
WebFontConfig = {
	google:{families:['Open+Sans:400,400italic,300,300italic,600,600italic,700italic,700:latin']}
};
(function(){
	var wf = document.createElement('script');
	wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js';
	wf.type = 'text/javascript';
	wf.async = 'true';
	var s = document.getElementsByTagName('script')[0];
	s.parentNode.insertBefore(wf, s);
})();
if(jQuery)(function($){
	//
	var HSelect = function(elem, options){
		this.elem = elem;
		this.$elem = $(elem);
		this.options = options;
	};
	HSelect.prototype = {
		defaults: {},
		init:function(){
			var self = this, options_length = self.$elem.children('option').length, $dropdown, $list;
			self.$elem.addClass('hidden').wrap('<div class="el-select" />').after('<a href="#" class="dropdown" />');
			$dropdown = self.$elem.next('.dropdown');
			$dropdown.text(self.$elem.children('option:selected') ? self.$elem.children('option:selected').text() : self.$elem.children('option').eq(0).text());
			$list = $('<span class="options" />').insertAfter($dropdown);
			for(var i = 0; i < options_length; i++){
				$('<a />', {
					text: self.$elem.children('option').eq(i).text(),
					rel: self.$elem.children('option').eq(i).val(),
					href: '#'
				}).appendTo($list);
			};
			var $items = $list.children('a');
			$dropdown.on('click', function(e){
				e.preventDefault();
				e.stopPropagation();
				$('.dropdown.active').each(function(){
					$(this).next('span.options').hide();
				});
				$(this).next('span.options').toggle();
			});
			$items.on('click', function(e){
				e.preventDefault();
				e.stopPropagation();
				$dropdown.text($(this).text());
				self.$elem.val($(this).attr('rel'));
				$list.hide();
				self.$elem.change();
			});
			$(document).click(function(){
				$list.hide();
			});
			return this;
		}
	}
	HSelect.defaults = HSelect.prototype.defaults;
	$.fn.hSelect = function(options){
		return this.each(function(){
			new HSelect(this, options).init();
		});
	};
	//
	var DHover = function(elem, options){
		this.elem = elem;
		this.$elem = $(elem);
		this.options = options;
	};
	DHover.prototype = {
		defaults: {},
		init:function(){
			var self = this, $tip = $('.un-db-tooltip', self.$elem);
			if($tip.length){
				$tip.hide();
				self.$elem.hover(function(){
					$tip.fadeIn();
				},function(){
					$tip.hide();
				});
			}
			return this;
		}
	}
	DHover.defaults = DHover.prototype.defaults;
	$.fn.dHover = function(options){
		return this.each(function(){
			new DHover(this, options).init();
		});
	};
	//
	var ASearch = function(elem, options){
		this.elem = elem;
		this.$elem = $(elem);
		this.options = options;
		self.$modal;
	};
	ASearch.prototype = {
		defaults: {},
		init:function(){
			var self = this;
			self.config = $.extend({}, self.defaults, self.options);
			self.$modal = $('.bl-sh-modal', self.$elem);
			self.$overlay = $('<div class="gl-modal-overlay" />');
			self.$r_element = $('.un-form-type input[type="radio"]', self.$modal);
			self.$f_element = $('div[data-radio-id]', self.$modal);
			self.$form = $('form', self.$modal);
			$('.el-modal', self.$elem).on('click', function(e){
				self._show();
				e.preventDefault();
			});
			if(!self.$r_element.filter(':checked').length){
				self.$r_element.eq(0).click();
			}
			self.$r_element.each(function(){
				if($(this).is(':checked')) self._change_form($(this));
				$(this).on('change', function(){
					self._change_form($(this));
				})
			})
			self.$form.on('submit', function(e){
				var $m = $('<span class="un-load" />');
				$.ajax({
					url:self.$form.prop('action'),
					dataType:'json',
					cache:false,
					type:'post',
					data:self.$form.serialize(),
					beforeSend:function(){
						self.$modal.append($m);
					},
					error:function(xhr, status, error){
						//$crt_data.empty().append('<div class="un-error">'+error+'</div>');
					},
					success:function(data){
						$m.remove();
						self._parse_json(data);
					}
				});
				e.preventDefault();
			})
			return this;
		},
		_change_form:function(radio){
			var self = this;
			self.$f_element.hide();
			$('.el-help', self.$modal).data('tooltip')._hide();
			self.$f_element.each(function(){
				if($(this).data('radio-id') == radio.prop('id')){
					$(this).show();
					$(this).find('input[type="text"]:first').focus();
				}
			});
		},
		_show:function(){
			var self = this;
			$('body').append(self.$overlay);
			self.$overlay.fadeTo(200, 1).on('click', function(){self._hide()});
			self.$modal.css({opacity:0}).fadeTo(200, 1);
		},
		_hide:function(){
			var self = this;
			$('.el-help', self.$modal).data('tooltip')._hide();
			self.$overlay.fadeTo(200, 0, function(){self.$overlay.remove()});
			self.$modal.fadeTo(200, 0, function(){self.$modal.hide()});
		},
		_parse_json:function(data){
			var self = this, $echo = $('<div class="bl-sh-data" />'), $radio = $('.un-form-type', self.$modal), $echo_text = '';
			$('.bl-sh-data', self.$modal).remove();
			$echo_text = '<span class="el-arrow"></span><span class="el-arrow-brd"></span>' +
				'<a class="el-close" href="#" title="Sluiten">Sluiten</a>' +
				'<div class="el-text' + ((data.result && data.result.length) ? ' small' : '') + '">' +
				'<p>' + data.message + '</p>' +
				'</div>';
			if(data.result && data.result.length){
				$echo_text += '<table class="el-tbl">';
				$.each(data.result, function(i, d){
					$echo_text += '<tr rel="' + d.link + '"><td>' + d.name + '</td><td>' + d.location + '</td><td>' + d.date + '</td><td>' + d.status + '</td></tr>';
				});
				$echo_text += '</table>';
			}
			$('.el-help', self.$modal).data('tooltip')._hide();
			$radio.hide().after($echo.html($echo_text));
			$('.el-tbl tr', $echo).hover(function(){
				$(this).addClass('el-hover')
			}, function(){
				$(this).removeClass('el-hover')
			}).on('click', function(){
				location.href = $(this).attr('rel');
			});
			$('.el-close', $echo).on('click', function(e){
				$echo.remove();
				$radio.show();
				e.preventDefault();
			});
		}
	}
	ASearch.defaults = ASearch.prototype.defaults;
	$.fn.aSearch = function(options){
		return this.each(function(){
			new ASearch(this, options).init();
		});
	};
	//
	var TabsDetails = function(elem, options){
		this.elem = elem;
		this.$elem = $(elem);
		this.options = options;
		this.content = '';
		this.$d = null; this.bh = null;
	};
	TabsDetails.prototype = {
		defaults: {
			headerElement:'.un-ds-tabs li',
			contentElement:'.un-ds-view',
			openItem:0
		},
		init:function(){
			var self = this;
			self.config = $.extend({}, self.defaults, self.options);
			var $headers = $(self.config.headerElement, self.$elem), $content = $(self.config.contentElement, self.$elem);
			$headers.each(function(i){
				var $this = $(this), $type = self._innerType($this, 'a');
				if($content.filter($type.attr('href')).length == 1){
					$content.filter($type.attr('href')).hide();
					$type.on('click', function(e){
						self._changeElement($this, self.d, $content);
						e.preventDefault();
					});
				}
			});
			self._innerType($headers.eq(self.config.openItem), 'a').click();
			return this;
		},
		_innerType:function(element, type){
			if(element) return element.children(type);
			else return false;
		},
		_changeElement:function(element, prev_element, content){
			var self = this, $current = self._innerType(element, 'a'), $previous = self._innerType(prev_element, 'span');
			self.d = element;
			if($previous){
				//if(element[0] === prev_element[0]) return false;
				prev_element.removeClass('el-active');
				$previous.replaceWith(
					$('<a />').html($previous.html()).prop({'title':$previous.attr('title'),'href':self.bh})
				);
				content.filter(self.bh).hide()
				self._innerType(prev_element, 'a').on('click', function(){
					self._changeElement(prev_element, self.d, content);
					return false;
				})
			}
			self.bh = $current.attr('href');
			element.addClass('el-active');
			$current.replaceWith(
				$('<span />').html($current.html()).attr({'title':$current.prop('title')})
			);
			content.filter(self.bh).show()
		}
	}
	TabsDetails.defaults = TabsDetails.prototype.defaults;
	$.fn.tabsDetails = function(options){
		return this.each(function(){
			new TabsDetails(this, options).init();
		});
	};
	//
	var EmulationInput = function(elem, options){
		this.elem = elem;
		this.$elem = $(elem);
		this.options = options;
	};
	EmulationInput.prototype = {
		defaults: {
			classCheckbox:'el-btn-chk',
			classRadio:'el-btn-rdo'
		},
		init:function(){
			var self = this;
			self.config = $.extend({}, self.defaults, self.options);
			if(self.$elem.prop('type') == 'checkbox'){
				if(!self.$elem.parents().hasClass(self.config.classCheckbox)){
					self.$elem.css({opacity:0, position:'absolute', left:'-99em'}).wrap($('<span />').addClass(self.config.classCheckbox));
					var $box = self.$elem.parent();
					$box.append('<em>&#10004;</em>');
					if(self.$elem.is(':checked')) $box.addClass('on');
					if(self.$elem.is(':disabled')) $box.addClass('disabled');
					$box.on('click', function(e){
						if(!$box.is('.disabled')){
							if(self.$elem.is(':checked')){
								self.$elem.prop('checked', false);
								$box.removeClass('on');
							}else{
								self.$elem.prop('checked', true);
								$box.addClass('on');
							}
							self.$elem.change();
							e.preventDefault(e);
						}else{return false}
					});
					self.$elem.parent('label').add('label[for="'+self.$elem.prop('id')+'"]').on('click', function(e){
						$box.click();
						e.preventDefault();
					});
					self.$elem.on('change', function(){
						if(self.$elem.is(':checked')) $box.addClass('on');
						else $box.removeClass('on');
					}).on('keydown', function(e){
						if(self.$elem.parent('label').length && (e.which == 13 || e.which == 32)) $box.click();
					}).on('focus', function(){
						if(!$box.is('.disabled')) $box.addClass('focused');
					}).on('blur', function(){
						$box.removeClass('focused');
					}).on('refresh', function(){
						if(self.$elem.is(':checked')) $box.addClass('on');
						else $box.removeClass('on');
						if(self.$elem.is(':disabled')) $box.addClass('disabled');
						else $box.removeClass('disabled');
					});
				}
			}else if(self.$elem.prop('type') == 'radio'){
				if(!self.$elem.parents().hasClass(self.config.classRadio)){
					self.$elem.css({opacity:0, position:'absolute', left:'-99em'}).wrap($('<span />').addClass(self.config.classRadio));
					var $box = self.$elem.parent();
					$box.append('<em>&#10004;</em>');
					if(self.$elem.is(':checked')) $box.addClass('on');
					if(self.$elem.is(':disabled')) $box.addClass('disabled');
					$box.on('click', function(e){
						if(!$box.is('.disabled')){
							$('input[name="'+self.$elem.prop('name')+'"]').prop('checked', false).parent().removeClass('on');
							self.$elem.prop('checked', true)
							$box.addClass('on');
							self.$elem.change();
							e.preventDefault();
						}else{return false}
					});
					self.$elem.parent('label').add('label[for="'+ self.$elem.prop('id')+'"]').on('click', function(e){
						$box.click();
						e.preventDefault();
					});
					self.$elem.on('change', function(){
						$('input[name="'+self.$elem.prop('name')+'"]').parent().removeClass('on');
						$box.addClass('on');
					}).on('focus', function(){
						if(!$box.is('.disabled')) $box.addClass('focused');
					}).on('blur', function(){
						$box.removeClass('focused');
					}).on('refresh', function(){
						if(self.$elem.is(':checked')){
							$('input[name="'+self.$elem.prop('name')+'"]').parent().removeClass('on');
							$box.addClass('on');
						}else $box.removeClass('on');
						if(self.$elem.is(':disabled')) $box.addClass('disabled');
						else $box.removeClass('disabled');
					});
				}
			}
			return this;
		}
	}
	EmulationInput.defaults = EmulationInput.prototype.defaults;
	$.fn.emulationInput = function(options){
		return this.each(function(){
			new EmulationInput(this, options).init();
		});
	};
	//
	var ATooltip = function(elem, options){
		this.elem = elem;
		this.$elem = $(elem);
		this.options = options;
		this.$tooltip;
		this.$elem.data("tooltip", this);
	};
	ATooltip.prototype = {
		defaults: {
			position:'n',
			click:true
		},
		init:function(){
			var self = this, content;
			self.config = $.extend({}, self.defaults, self.options);
			if(self.elem.hash != undefined && $(self.elem.hash).length){
				content = $(self.elem.hash).html();
			}else if(self.$elem.prop('title').length){
				content = self.$elem.prop('title');
			}else{return true}
			self.config.position = self.$elem.data('position') ? self.$elem.data('position') : self.config.position;
			//self.$elem.prop('title','').html($('<span />'));
			self.$elem.wrapInner('<span />');
			self._create(content);
			if(!self.config.click){	
				self.$elem.on('mouseenter', function(){
					self._show();
				}).on('mouseleave', function(){
					self._hide();
				});
			}else{
				self.$elem.on('click', function(e){
					self._show();
					self.$elem.addClass('active');
					$(window).on('tooltip_move', function(){self._position()})
					self.$tooltip.find('.el-close').on('click', function(e_i){
						$(window).off('tooltip_move');
						self._hide();
						e_i.preventDefault();
					});
					e.preventDefault();
				});
				$(window).on('resize', function(){$(this).trigger('tooltip_move')});
			}
			return this;
		},
		_create:function(content){
			var self = this, $close = (!self.config.click) ? '' : '<a class="el-close" href="#" title="Sluiten">Sluiten</a>';
			self.$tooltip = $('<div />').addClass('bl-tip').append(
				content,
				$close,
				'<span class="el-arrow ' + self.config.position + '" />',
				'<span class="el-arrow-brd ' + self.config.position + '" />'
			);
		},
		_show:function(){
			this._hide();
			$('body').append(this.$tooltip);
			this._position();
		},
		_hide:function(){
			$('.bl-tip').remove();
		},
		_position:function(){
			var self = this, position_icon = self.$elem.offset();
			if(self.config.position == 'e'){
				self.$tooltip.css({
					top:(position_icon.top - (self.$tooltip.innerHeight() / 2) + 7),
					left:(position_icon.left - self.$tooltip.outerWidth() - 9)
				});
			}else if(self.config.position == 's'){
				self.$tooltip.css({
					top:(position_icon.top + self.$elem.height() + 9),
					left:(position_icon.left + (self.$elem.width() / 2) - 54)
				});
			}else if(self.config.position == 'w'){
				self.$tooltip.css({
					top:(position_icon.top - (self.$tooltip.innerHeight() / 2) + 7),
					left:(position_icon.left + self.$elem.width() + 9)
				});
			}else{
				self.$tooltip.css({
					top:(position_icon.top - self.$tooltip.outerHeight() - 9),
					left:(position_icon.left + (self.$elem.width() / 2) - 54)
				});
			}
		}
	}
	ATooltip.defaults = ATooltip.prototype.defaults;
	$.fn.aTooltip = function(options){
		return this.each(function(){
			new ATooltip(this, options).init();
		});
	};
	//
	var AModal = function(elem, options){
		this.elem = elem;
		this.$elem = $(elem);
		this.options = options;
		this.content = '';
		this.$modal; this.$overlay;
	};
	AModal.prototype = {
		defaults: {
			searchModal:false,
			customObject:false,
			overlayAction:true
		},
		init:function(){
			var self = this;
			self.config = $.extend({}, self.defaults, self.options);
			if(self.config.customObject){
				self.$modal = $(self.config.customObject);
			}else if(self.elem.hash != undefined && $(self.elem.hash).length){
				self.$modal = $(self.elem.hash);
			}else{return true}
			self.$modal.append('<a class="el-close" href="#" title="Sluiten">Sluiten</a>'), self.$overlay = $('<div class="gl-modal-overlay" />');
			$('.el-close', self.$modal).on('click', function(e){
				self._hide();
				e.preventDefault();
			})
			self.$elem.on('click', function(e){
				self._show();
				e.preventDefault();
			});
			return this;
		},
		_show:function(){
			var self = this, modal_w, modal_h;
			$('body').append(self.$overlay);
			if(self.config.overlayAction){
				self.$overlay.on('click', function(){self._hide()});
			}
			if(self.config.searchModal){
				self.$modal.css({opacity:0, position:'absolute', zIndex:1100}).fadeTo(200, 1);
			}else{
				self.$modal.css({display:'block', position:'fixed', zIndex:1100, top:'-999em', left:'-999em'});
				modal_w = self.$modal.innerWidth(), modal_h = self.$modal.innerHeight();
				self.$modal.css({opacity:0, left:'50%', marginLeft:-(modal_w/2), top:($(window).height()-modal_h)/2}).fadeTo(200, 1);
			}
			self.$overlay.fadeTo(200, 1);
		},
		_hide:function(){
			var self = this;
			self.$overlay.fadeTo(200, 0, function(){self.$overlay.remove()});
			self.$modal.fadeTo(200, 0, function(){self.$modal.hide()});
		}
	}
	AModal.defaults = AModal.prototype.defaults;
	$.fn.aModal = function(options){
		return this.each(function(){
			new AModal(this, options).init();
		});
	};
	//
	$.fn.accordWithIcon = function(params){
		var conf = $.extend({
			headElement:'dt',
			bodyElement:'dd'
		}, params);
		return this.each(function(){
			var c=conf, o=$(this);
			o.children().each(function(){
				if($(this).is(c.headElement)){
					if($(this).next().is(c.bodyElement)){
						var heading=$(this), hull=$(this).next();
						hull.hide();
						if(hull.html()!=''){
							var head_icon=$('<span class="el-icon">+</span>'),
									head_anchor=$('<a href="#"></a>').html(heading.html());
							heading.empty().append(head_icon).append(head_anchor).addClass('el-close');
							head_anchor.on('click', function(e){
								head_icon.trigger('click');
								e.preventDefault();
							});
							head_icon.on('click', function(){
								if(heading.hasClass('el-close')){
									hull.stop().slideDown();
									heading.removeClass('el-close');
									head_icon.html('-');
								}else{
									hull.stop().slideUp();
									heading.addClass('el-close');
									head_icon.html('+');
								}
							});
						}
						if($(this).hasClass('el-open')){
							hull.show();
							heading.removeClass('el-close').removeClass('el-open');
							head_icon.html('-');
						}
					}
				}
			})
		})
	};
	//
	$.fn.actionDetails = function(params){
		var conf=$.extend({
			toolTip:'.el-help',
			addressShow:'el-form-address',
			addressBlock:'.un-ds-address',
			criteriaShow:'el-form-criteria',
			criteriaBlock:'.un-ds-criteria',
			accordBlock:'dl.un-ds-reg',
			sideToPrint:'.un-ds-note'
		}, params);
		return this.each(function(){
			var	c=conf, $o=$(this), $tip=$(c.toolTip, $o), $inp=$('input[type="checkbox"], input[type="radio"]', $o), $adr_input=$('.'+c.addressShow, $o), $adr_block=$(c.addressBlock, $o), $crt_input=$('.'+c.criteriaShow, $o), $crt_block=$(c.criteriaBlock, $o), $acrd=$(c.accordBlock, $o), $acrd_close=$('<a class="el-close" href="#" title="Sluiten">Sluiten</a>');
			$o.find('.un-ds-ttl').after($(c.sideToPrint).clone())
			//$tip.aTooltip({tipPosition:'right', xOffset:10, yOffset:30, tipClass:'bl-ds-tip'});
			$inp.emulationInput();
			$acrd.accordWithIcon();
			$acrd.children('dd').append('<span class="el-arrow"></span><span class="el-arrow-brd"></span>', $acrd_close)
			$acrd_close.on('click', function(){
				$acrd.find('dt .el-icon').trigger('click');
				return false;
			})
			if($adr_input.length==1 && $adr_block.length==1){
				$adr_input.on('change', function(){
					if($(this).is(':checked')){
						$adr_block.show();
					}else{
						$adr_block.hide();
					}
					$(window).resize();
				})
				if($adr_input.is(':checked')){$adr_block.show()}else{$adr_block.hide()}
			};
			
			if($crt_input.length==1 && $crt_block.length==1){
				$o.find($('input[type="radio"]').prop('name',$crt_input.prop('name'))).each(function(){
					$(this).on('change', function(){
						if($crt_input.is(':checked')){
							$crt_block.show();
						}else{
							$crt_block.hide();
						}
						$(window).resize();
					})
				});
				if($crt_input.is(':checked')){$crt_block.show()}else{$crt_block.hide()}
			}
			
		})
	};
	//
	$.fn.actionSettings = function(params){
		var conf=$.extend({
			passwordBlock:'.un-st-pass',
			criteriaBlock:'.un-st-crit',
			criteriaUrl:'include/criteria.php'
		}, params);
		return this.each(function(){
			var	c=conf, $o=$(this), f=this, $psw_block=$(c.passwordBlock, $o), $crt_block=$(c.criteriaBlock, $o), $crt_data;
			$.extend(f,{
				_psw_check:function(){
					var $btn=$('button', $psw_block), $new_psw=$('input#new_passw', $psw_block), $new_psw_rpt=$('input#new_passw_rep', $psw_block);
					if($btn.length==1 && $new_psw.length==1 && $new_psw_rpt.length==1){
						$btn.prop('disabled', true);
						f._psw_inp($new_psw, $new_psw_rpt, $btn);
						f._psw_inp($new_psw_rpt, $new_psw, $btn)
					}
				},
				_psw_inp:function(c_inp, h_inp, btn){
					c_inp.on('change keyup', function(){
						if(c_inp.val().length && c_inp.val()==h_inp.val()){
							btn.prop('disabled', false);
						}else{
							btn.prop('disabled', true);
						}
					});
				},
				_crt_init:function(){
					var $form=$('.un-generic-form', $crt_block), $inp, $btn;
					$form.append(
						'<div class="un-row cf">'
							+'<label for="new_crit">Voer een criterium in</label>'
							+'<input id="new_crit" type="text" name="new_crit" value="">'
							+'<button type="submit" disabled="disabled" class="el-btn-blue"><span>Toevoegen</span></button>'
						+'</div>')
					$inp=$form.find('input[type="text"]'), $btn=$form.find('button'), $crt_data=$('.un-generic', $crt_block);
					$inp.on('change keyup', function(e){
						if($inp.val().length){
							$btn.prop('disabled', false);
						}else{
							$btn.prop('disabled', true);
						}
						if($inp.val().length && e.keyCode==13){$btn.click()}
					});
					$btn.on('click', function(){
						f._crt_update($inp);
						return false;
					});
					f._crt_load();
				},
				_crt_load:function(){
					$.ajax({
						url:c.criteriaUrl,
						dataType:'json',
						cache:false,
						beforeSend:function(){
							$('.un-row', $crt_data).hide();
							$crt_data.append('<p>Loading...</p>');
						},
						error:function(xhr, status, error){
							$crt_data.empty().append('<div class="un-error">'+error+'</div>');
						},
						success:function(data){
							f._parse_json(data);
						}
					});
				},
				_crt_edit:function($in_data){
					var $v_data=$in_data.find('.el-name');
					$in_data.find('.el-name, .el-edit, .el-up, .el-down, .el-del').hide();
					$in_data.append(
						'<li class="el-form-edit">'
							+'<input id="edit_crit" type="text" name="edit_crit" value="'+$v_data.text()+'">'
							+'<button type="submit" class="el-btn-blue"><span>Bewaren</span></button>'
						+'</li>');
					var $i_data=$in_data.find('input[type="text"]'),$b_data=$in_data.find('button');
					$i_data.focus();
					$i_data.on('change keyup', function(e){
						if($i_data.val().length){
							$b_data.prop('disabled', false);
						}else{
							$b_data.prop('disabled', true);
						}
						if($i_data.val().length && e.keyCode==13){$b_data.click()}
						if(e.keyCode==27){$in_data.find('.el-name, .el-edit, .el-up, .el-down, .el-del').show(); $in_data.find('.el-form-edit').remove()}
					});
					$b_data.on('click', function(){
						$v_data.prop('title', $i_data.val()).text($i_data.val())
						f._crt_update();
						return false;
					});
				},
				_crt_update:function(in_inp){
					var jqdata=[];
					$('.un-row', $crt_data).each(function(){
						var jqitem={};
						if($(this).find('.el-date').text().length){
							jqitem.date=$(this).find('.el-date').text();
						}
						jqitem.name=$(this).find('.el-name').text();
						jqdata.push(jqitem)
					});
					if(in_inp!=undefined){jqdata.push({"name":in_inp.val()})}
					$.ajax({
						url:c.criteriaUrl,
						dataType:'json',
						cache:false,
						type:'post',
						data:{"criteria_save":JSON.stringify(jqdata)},
						beforeSend:function(){
							$crt_data.css({minHeight:$crt_data.height()})
							$('.un-row', $crt_data).hide();
							$crt_data.append('<p>Loading...</p>');
						},
						error:function(xhr, status, error){
							$crt_data.empty().append('<div class="un-error">'+error+'</div>');
						},
						success:function(data){
							f._parse_json(data);
							$crt_data.css({minHeight:0});
						}
					});
				},
				_parse_json:function(d){
					$crt_data.empty();
					$.each(d, function(i){
						$crt_data.append('<ul class="un-row cf">'
							+'<li class="el-date">'+(this.date?this.date:'')+'</li>'
							+'<li class="el-name"><span title="'+this.name+'">'+this.name+'</span></li>'
							+'<li class="el-edit"><a href="#" title="Wijzigen">Wijzigen</a></li>'
							+'<li class="el-del"><a href="#" title="Verwijderen">Verwijderen</a></li>'
							+'<li class="el-up">'+(i?'<a href="#" title="Omhoog">Omhoog</a>':'<span></span>')+'</li>'
							+'<li class="el-down">'+(i==d.length-1?'<span></span>':'<a href="#" title="Omlaag">Omlaag</a>')+'</li>'
						+'</ul>');
					})
					$('.un-row', $crt_data).each(function(i){
						var rw=$(this);
						$(this).find('.el-del a').on('click', function(){
							rw.remove();
							f._crt_update();
							return false;
						});
						$(this).find('.el-up a').on('click', function(){
							$('.un-row', $crt_data).eq(i-1).before(rw);
							f._crt_update();
							return false;
						});
						$(this).find('.el-down a').on('click', function(){
							$('.un-row', $crt_data).eq(i+1).after(rw);
							f._crt_update();
							return false;
						});
						$(this).find('.el-edit a').on('click', function(){
							f._crt_edit($('.un-row', $crt_data).eq(i));
							return false;
						});
					})
				}
			});
			$o.find('.un-st-accord').accordWithIcon({headElement:'h3', bodyElement:'.un-st-data'});
			f._psw_check();
			f._crt_init();
		})
	};
	//
	$.fn.eqElements = function(params){
		var conf=$.extend({
			elementGet:'.bl-dm-form, .bl-dm-list'
		}, params);
		return this.each(function(){
			var	c=conf, el=$(c.elementGet, $(this)), height=0;
			el.each(function(){
				height=Math.max(height, $(this).height());
			});
			el.each(function(){
				$(this).css('height', height);
			});
		})
	};
	//
	$.fn.placeholderInput = function(params){
		var conf=$.extend({
			classDef:'el-def'
		}, params);
		return this.each(function(){
			var f=this;
			if(f.placeholder && 'placeholder' in document.createElement(f.tagName)) return;
			var $o=$(this), c=conf, placeholder = f.getAttribute('placeholder');
			if(f.value === '' || f.value == placeholder){
				$o.addClass(c.classDef);
				f.value=placeholder;
			}
			$o.on('focus', function(){
				if($o.hasClass(c.classDef)){
					this.value='';
					$o.removeClass(c.classDef)
				}
			}).on('blur', function(){
				if(this.value === ''){
					$o.addClass(c.classDef);
					this.value=placeholder;
				}else{
					$o.removeClass(c.classDef);
				}
			});
			f.form && $(f.form).submit(function(){
				if($o.hasClass(c.classDef)){
					that.value='';
				}
			});
		})
	};
	//
	$.fn.searchChange = function(params){
		var conf=$.extend({
			elementForm:'div[data-radio-id]',
			elementChange:'.un-form-type input[type="radio"]'
		}, params);
		return this.each(function(){
			var	c=conf, f=this, $o=$(this), $r_element=$(c.elementChange, $o), $f_element=$o.find(c.elementForm), $tbs=$('.bl-ls-tabs a', $o), $m_inp=$('#code_brief', $o);
			$.extend(f,{
				_eq_tabs:function(){
					$tbs.css({'height':'auto'});
					$tbs.css({'height':$o.innerHeight()-50});
				},
				_change_form:function(rd, fs){
					$f_element.hide(); $('.bl-form-tip').hide();
					$f_element.each(function(){
						if($(this).data('radio-id')==rd.prop('id')){
							$(this).show();
							var $inp=$(this).find('input[type="text"]:first');
							if($inp.data('hint') && fs){
								$inp.focus();
								$inp.aTooltip({ifLoad:true, tipClass:'bl-form-tip', tipCustom:'#'+$inp.data('hint'), xOffset:95, yOffset:12});
								$('.bl-form-tip').find('tr').hover(function(){$(this).addClass('el-hover')}, function(){$(this).removeClass('el-hover')});
							}
						}
						
					});
					f._eq_tabs();
				}
			});
			var m_inp_v=$m_inp.val();
			$m_inp.mask('a-9999-9999').val(m_inp_v);
			if(!$r_element.filter(':checked').length){
				$r_element.eq(0).click();
			}
			$r_element.each(function(){
				var $rd=$(this);
				if($rd.is(':checked')){
					f._change_form($rd, true);
				}
				$rd.on('change', function(){
					f._change_form($rd);
				})
			})
			$r_element.emulationInput();
		})
	};
	//
	$.fn.actionTable = function(params){
		var conf = $.extend({
			tableElement:'table',
			checkboxInTable:'td.el-chk input[type="checkbox"]',
			checkboxAll:'.un-ls-action input[type="checkbox"]',
			sortFunction:undefined
		}, params);
		return this.each(function(){
			var $o=$(this), c=conf, f=this, $table=$(c.tableElement, $o), $chb_table=$(c.checkboxInTable, $table), $chb_all=$(c.checkboxAll, $o), state, $fx_head=$('<div class="bl-ls-fixed bl-ls"></div>'), sort_function;
			if(!$table.length) return false;
			sort_function={
        'int':function(a,b){return parseInt(a, 10) - parseInt(b,10)},
        'float':function(a,b){return parseFloat(a) - parseFloat(b)},
        'string':function(a,b){if(a<b) return -1; if(a>b) return +1; return 0},
				'l-word':function(a,b){
					var a_r=a.split(" "), b_r=b.split(" ");
					if(a_r[a_r.length-1].toUpperCase()<b_r[b_r.length-1].toUpperCase()) return -1; if(a_r[a_r.length-1].toUpperCase()>b_r[b_r.length-1].toUpperCase()) return +1; return 0
				},
				'date':function(a,b){aDate=f._date_from_string(a); bDate=f._date_from_string(b); return aDate-bDate},
				'reverse-string':function(a,b){if(b<a) return -1; if(b>a) return +1; return 0}
      };
			$.extend(f,{
				_arrays_equal:function(a,b){return !!a && !!b && !(a<b || b<a)},
				_date_from_string:function(str){
					var pattern=str.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);
					return (pattern) ? new Date(pattern[3], pattern[2]-1, pattern[1]) : null;
				},
				_move:function(){
					$fx_head.append($('<table></table>').append($table.find('thead').clone()));
					$('body').append($fx_head.width($table.width()));
					f._scroll_check();
					$fx_head.find('th').each(function(i){
						$(this).on('click', function(){
							$table.find('thead th').eq(i).trigger('click');
						})
					})
					$(window).on('scroll resize',function() {
						f._scroll_check();
					});
				},
				_scroll_check:function(){
  				var scr_top=$(window).scrollTop(), tbl_top=$table.offset().top, tbl_btm=$table.height()+tbl_top-$fx_head.height();
  				if(tbl_top<scr_top && tbl_btm>scr_top){
						if(_ie7){
							$fx_head.css({position:'absolute', top:scr_top, left:$table.offset().left});
						}else{
							$fx_head.css({position:'fixed', top:0, left:$table.offset().left-$(window).scrollLeft()});
						}
  					$fx_head.show();
  				}else if(tbl_top>scr_top){
						$fx_head.hide();
					}else{
  					$fx_head.css({position:'absolute', top:tbl_btm, left:$table.offset().left});
  					$fx_head.show();
  				}
				},
				_chb_tbl_emulation:function(){
					$chb_table.each(function(){
						var $chb=$(this);
						$chb.css({opacity:0}).wrap('<span class="el-btn-chk"></span>');
						$chb.on('change', function(){
							if($chb.is(':checked')){
								$chb.parent().addClass('el-btn-chk-on');
								$chb.parents('tr').addClass('el-selected');
							}else{
								$chb.parent().removeClass('el-btn-chk-on');
								$chb.parents('tr').removeClass('el-selected');
							}
						})
					});
				},
				_chb_all_emulation:function(){
					$chb_all.each(function(){
						var $chb=$(this);
						$chb.css({opacity:0}).wrap('<span class="el-btn-chk"></span>');
						$chb.on('change', function(){
							if(state==undefined){state=$chb.prop('checked')}
							if(state){
								$chb.parent().addClass('el-btn-chk-on').removeClass('el-btn-chk-few');
								//$table.addClass('un-tbl-chk')
							}else{
								$chb.parent().removeClass('el-btn-chk-on');
								//$table.removeClass('un-tbl-chk')
								if($chb_table.filter(":checked").length){
									$chb.parent().addClass('el-btn-chk-few');
									//$table.addClass('un-tbl-chk')
								}else{
									$chb.parent().removeClass('el-btn-chk-few');
								}
							}
						})
					});
				},
				_checkbox_action:function(){
					f._chb_tbl_emulation(); f._chb_all_emulation();
					$chb_all.on('click', function(e){
						state=$(e.currentTarget).prop('checked');
						$chb_all.prop('checked', state).change();
						$chb_table.prop('checked', state).change();
					}).change();
					$chb_table.on('click', function(e){
						state=$chb_table.filter(":not(:checked)").length === 0;
						$chb_all.prop('checked', state).change();
					}).change()
					
				},
				_sort_map:function(arr, sorting, reverse_column){
					var map=[], index=0;
					if(reverse_column){
						for(var i=arr.length-1; i >= 0; i--){map.push(i)}
					}else{
						var sorted=arr.slice(0).sort(sorting);
						for(var i=0; i<arr.length; i++){
							index=$.inArray(arr[i], sorted);
							while($.inArray(index, map) != -1){index++}
							map.push(index);
						}
					}
					return map;
				},
				_apply_sort_map:function(arr, map){
					var clone=arr.slice(0), newIndex=0;
					for(var i=0; i<map.length; i++){
						newIndex = map[i];
						clone[newIndex] = arr[i];
					}
					return clone;
				},
				_apply_sort_th:function(obj, in_this, in_sort){
					obj.find('th').data('sort-dir', null).removeClass('el-sort-desc el-sort-asc').find('.el-arrow').remove();
          in_this.data('sort-dir', in_sort).addClass('el-sort-'+in_sort).append('<span class="el-arrow"></span>');
				}
			});
			$table.find('th[title]').each(function(){
				$(this).aTooltip({tipClass:'bl-tbl-tip'});
			});
			$table.find('tbody tr').hover(function(){
				$(this).addClass('row-hover');
			},function(){
				$(this).removeClass('row-hover');
			});
			//f._checkbox_action();
			f._move();
			$table.on('click', 'th', function(){
        var trs=$table.children('tbody').children('tr'), $this=$(this), th_index=0, dir={ASC:'asc', DESC:'desc'};
        $table.find('th').slice(0, $this.index()).each(function(){
          var cols=$(this).attr('colspan') || 1;
          th_index+=parseInt(cols,10);
        });
        var sort_dir=$this.data('sort-dir') === dir.ASC ? dir.DESC : dir.ASC;
        if(sort_dir==dir.DESC)
          var type=$this.data('sort-desc') || $this.data('sort') || null;
        else
          var type=$this.data('sort') || null;
        if(type===null) return;
        $table.trigger('beforetablesort', {column:th_index, direction:sort_dir});
        $table.css('display');
        setTimeout(function(){
          var column=[], sortMethod=sort_function[type];
          trs.each(function(index,tr){
            var $e = $(tr).children().eq(th_index);
            var sort_val=$e.data('sort-value'), order_by=typeof(sort_val) !== 'undefined' ? sort_val : $e.text();
            column.push(order_by);
          });
          var reverse_column=!!$this.data('sort-dir') && !$this.data('sort-desc'), theMap=f._sort_map(column, sortMethod, reverse_column);
          f._apply_sort_th($table, $table.find('th').eq(th_index), sort_dir);
					f._apply_sort_th($fx_head, $fx_head.find('th').eq(th_index), sort_dir);
          var sortedTRs = $(f._apply_sort_map(trs, theMap));
          $table.children('tbody').append(sortedTRs);
          $table.trigger('aftertablesort', {column:th_index, direction:sort_dir});
          $table.css('display');
        }, 10);
      });
		});
	};
	//
})(jQuery);
var _ie7=false; if(document.all && !document.querySelector){_ie7=true}
/* json2.js
 * 2008-01-17
 * Public Domain
 * No warranty expressed or implied. Use at your own risk.
 * See http://www.JSON.org/js.html
*/
if(!this.JSON){JSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toJSON=function(){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};function stringify(value,whitelist){var a,i,k,l,r=/["\\\x00-\x1f\x7f-\x9f]/g,v;switch(typeof value){case'string':return r.test(value)?'"'+value.replace(r,function(a){var c=m[a];if(c){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"':'"'+value+'"';case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
if(typeof value.toJSON==='function'){return stringify(value.toJSON());}
a=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){l=value.length;for(i=0;i<l;i+=1){a.push(stringify(value[i],whitelist)||'null');}
return'['+a.join(',')+']';}
if(whitelist){l=whitelist.length;for(i=0;i<l;i+=1){k=whitelist[i];if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}else{for(k in value){if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}
return'{'+a.join(',')+'}';}}
return{stringify:stringify,parse:function(text,filter){var j;function walk(k,v){var i,n;if(v&&typeof v==='object'){for(i in v){if(Object.prototype.hasOwnProperty.apply(v,[i])){n=walk(i,v[i]);if(n!==undefined){v[i]=n;}}}}
return filter(k,v);}
if(/^[\],:{}\s]*$/.test(text.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof filter==='function'?walk('',j):j;}
throw new SyntaxError('parseJSON');}};}();}
/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2013 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
	Version: 1.3.1
*/
(function(e){function t(){var e=document.createElement("input"),t="onpaste";return e.setAttribute(t,""),"function"==typeof e[t]?"paste":"input"}var n,a=t()+".mask",r=navigator.userAgent,i=/iphone/i.test(r),o=/android/i.test(r);e.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},dataName:"rawMaskFn",placeholder:"_"},e.fn.extend({caret:function(e,t){var n;if(0!==this.length&&!this.is(":hidden"))return"number"==typeof e?(t="number"==typeof t?t:e,this.each(function(){this.setSelectionRange?this.setSelectionRange(e,t):this.createTextRange&&(n=this.createTextRange(),n.collapse(!0),n.moveEnd("character",t),n.moveStart("character",e),n.select())})):(this[0].setSelectionRange?(e=this[0].selectionStart,t=this[0].selectionEnd):document.selection&&document.selection.createRange&&(n=document.selection.createRange(),e=0-n.duplicate().moveStart("character",-1e5),t=e+n.text.length),{begin:e,end:t})},unmask:function(){return this.trigger("unmask")},mask:function(t,r){var c,l,s,u,f,h;return!t&&this.length>0?(c=e(this[0]),c.data(e.mask.dataName)()):(r=e.extend({placeholder:e.mask.placeholder,completed:null},r),l=e.mask.definitions,s=[],u=h=t.length,f=null,e.each(t.split(""),function(e,t){"?"==t?(h--,u=e):l[t]?(s.push(RegExp(l[t])),null===f&&(f=s.length-1)):s.push(null)}),this.trigger("unmask").each(function(){function c(e){for(;h>++e&&!s[e];);return e}function d(e){for(;--e>=0&&!s[e];);return e}function m(e,t){var n,a;if(!(0>e)){for(n=e,a=c(t);h>n;n++)if(s[n]){if(!(h>a&&s[n].test(R[a])))break;R[n]=R[a],R[a]=r.placeholder,a=c(a)}b(),x.caret(Math.max(f,e))}}function p(e){var t,n,a,i;for(t=e,n=r.placeholder;h>t;t++)if(s[t]){if(a=c(t),i=R[t],R[t]=n,!(h>a&&s[a].test(i)))break;n=i}}function g(e){var t,n,a,r=e.which;8===r||46===r||i&&127===r?(t=x.caret(),n=t.begin,a=t.end,0===a-n&&(n=46!==r?d(n):a=c(n-1),a=46===r?c(a):a),k(n,a),m(n,a-1),e.preventDefault()):27==r&&(x.val(S),x.caret(0,y()),e.preventDefault())}function v(t){var n,a,i,l=t.which,u=x.caret();t.ctrlKey||t.altKey||t.metaKey||32>l||l&&(0!==u.end-u.begin&&(k(u.begin,u.end),m(u.begin,u.end-1)),n=c(u.begin-1),h>n&&(a=String.fromCharCode(l),s[n].test(a)&&(p(n),R[n]=a,b(),i=c(n),o?setTimeout(e.proxy(e.fn.caret,x,i),0):x.caret(i),r.completed&&i>=h&&r.completed.call(x))),t.preventDefault())}function k(e,t){var n;for(n=e;t>n&&h>n;n++)s[n]&&(R[n]=r.placeholder)}function b(){x.val(R.join(""))}function y(e){var t,n,a=x.val(),i=-1;for(t=0,pos=0;h>t;t++)if(s[t]){for(R[t]=r.placeholder;pos++<a.length;)if(n=a.charAt(pos-1),s[t].test(n)){R[t]=n,i=t;break}if(pos>a.length)break}else R[t]===a.charAt(pos)&&t!==u&&(pos++,i=t);return e?b():u>i+1?(x.val(""),k(0,h)):(b(),x.val(x.val().substring(0,i+1))),u?t:f}var x=e(this),R=e.map(t.split(""),function(e){return"?"!=e?l[e]?r.placeholder:e:void 0}),S=x.val();x.data(e.mask.dataName,function(){return e.map(R,function(e,t){return s[t]&&e!=r.placeholder?e:null}).join("")}),x.attr("readonly")||x.one("unmask",function(){x.unbind(".mask").removeData(e.mask.dataName)}).bind("focus.mask",function(){clearTimeout(n);var e;S=x.val(),e=y(),n=setTimeout(function(){b(),e==t.length?x.caret(0,e):x.caret(e)},10)}).bind("blur.mask",function(){y(),x.val()!=S&&x.change()}).bind("keydown.mask",g).bind("keypress.mask",v).bind(a,function(){setTimeout(function(){var e=y(!0);x.caret(e),r.completed&&e==x.val().length&&r.completed.call(x)},0)}),y()}))}})})(jQuery);
